﻿namespace h2
{
    public class Student
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }

        public Student(int id, string name, int age)
        {
            Id = id;
            Name = name;
            Age = age;
        }

        public override string ToString()
        {
            return $"学号: {Id}, 姓名: {Name}, 年龄: {Age}";
        }
    }

    public class Class
    {
        private List<Student> _students;
        public string ClassName { get; set; }

        public Class(string className)
        {
            ClassName = className;
            _students = new List<Student>();
        }

        public Student this[int index]
        {
            get
            {
                if (index < 0 || index >= _students.Count)
                {
                    throw new IndexOutOfRangeException("索引超出范围");
                }
                return _students[index];
            }
            set
            {
                if (index < 0 || index >= _students.Count)
                {
                    throw new IndexOutOfRangeException("索引超出范围");
                }
                _students[index] = value;
            }
        }

        public void AddStudent(Student student)
        {
            _students.Add(student);
        }

        public int StudentCount => _students.Count;
    }

    class Program
    {
        static void Main(string[] args)
        {
            // 创建班级对象
            Class class1 = new Class("高一(1)班");

            // 添加学生
            class1.AddStudent(new Student(101, "张三", 16));
            class1.AddStudent(new Student(102, "李四", 17));
            class1.AddStudent(new Student(103, "王五", 16));

            Console.WriteLine($"====={class1.ClassName}学生列表=====");

            // 通过索引访问学生
            for (int i = 0; i < class1.StudentCount; i++)
            {
                Console.WriteLine($"索引 {i}: {class1[i]}");
            }

            // 通过索引修改学生信息
            class1[1] = new Student(102, "李四", 18);
            Console.WriteLine("\n修改后的数据:");
            Console.WriteLine($"索引 1: {class1[1]}");

            // 测试索引越界
            try
            {
                Console.WriteLine(class1[3]);  // 索引3超出范围（只有0,1,2三个索引）
            }
            catch (IndexOutOfRangeException ex)
            {
                Console.WriteLine($"\n错误: {ex.Message}");
            }
        }
    }

}

